﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
using GPSTrackingWebsiteManager.ClassManager;

namespace GPSTrackingWebsiteManager.Manager.Pages
{
    public partial class AdministratorsByDepartments : ClassManager.SessionManagerPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                GridSortExpression expression = new GridSortExpression();
                expression.FieldName = "DepartmentIdSource.Name";
                expression.SetSortOrder("Ascending");
                this.DeparmentsGrid.MasterTableView.SortExpressions.AddSortExpression(expression);

                expression = new GridSortExpression();
                expression.FieldName = GPSTrackingDBV2.Entities.AdministratorsColumn.AdminUsername.ToString();
                expression.SetSortOrder("Ascending");
                this.AdministratorsSelectedGrid.MasterTableView.SortExpressions.AddSortExpression(expression);
            }
        }

        protected void AdministratorsSelectedGrid_NeedDataSource(object sender, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
        {
            GetAdministratorsByCompanyIDByDepartmentID(getSessionManager().CompanyIDSelectedComboBox, getDepartmentIDSelected());
            ResizeGrids();
        }

        protected void GetAdministratorsByCompanyIDByDepartmentID(int companyID, int departmentID)
        {
            AdministratorsSelectedGrid.DataSource = GPSTrackingDBV2Custom.Data.DataRepository.AdministratorsProvider.GetAdministratorsByCompanyIDByDepartmentID(companyID, getDepartmentIDSelected());
        }

        protected void uscAdministratorsSearch_OnCancelEvent()
        {
            ResizeGrids();
        }

        protected void uscAdministratorsSearch_OnAcceptEvent(List<GridDataItem> rows)
        {
            string AdminUsername;
            int departmentID = getDepartmentIDSelected();
            int companyID = getSessionManager().CompanyIDSelectedComboBox;
            GPSTrackingDBV2.Entities.AdministratorsByDepartments AdministratorsByDepartmentsEntity = new GPSTrackingDBV2.Entities.AdministratorsByDepartments();

            foreach (GridDataItem row in rows)
            {
                try
                {
                    if (departmentID == -1)
                    {
                        ResizeGrids();
                        showErrorMessage("Debe selecionar un departamento para asociar las administradores.");
                        return;
                    }

                    AdminUsername = row.Cells[3].Text;

                    //Insert
                    AdministratorsByDepartmentsEntity.Dispose();
                    AdministratorsByDepartmentsEntity.CompanyId = companyID;
                    AdministratorsByDepartmentsEntity.DepartmentId = departmentID;
                    AdministratorsByDepartmentsEntity.AdminUsername = AdminUsername;

                    GPSTrackingDBV2.Data.DataRepository.AdministratorsByDepartmentsProvider.Insert(AdministratorsByDepartmentsEntity);

                }
                catch
                {
                    //
                }
            }
            uscAdministratorsSearch.GetAdministratorsGridToAssociate();
            GetAdministratorsByCompanyIDByDepartmentID(getSessionManager().CompanyIDSelectedComboBox, getDepartmentIDSelected());
            AdministratorsSelectedGrid.DataBind();
            ResizeGrids();

        }

        protected void AdministratorsSelectedGrid_DeleteCommand(object sender, GridCommandEventArgs e)
        {
            GPSTrackingDBV2.Data.TransactionManager tm = GPSTrackingDBV2.Data.DataRepository.Provider.CreateTransaction();
            try
            {
                tm.BeginTransaction();
                GridEditableItem item = e.Item as GridEditableItem;
                Hashtable Entity = new Hashtable();
                item.ExtractValues(Entity);

                GPSTrackingDBV2.Data.DataRepository.AdministratorsByDepartmentsProvider.Delete(tm, Entity["AdminUsername"].ToString(), getSessionManager().CompanyIDSelectedComboBox, getDepartmentIDSelected());
                tm.Commit();
            }
            catch (Exception ex)
            {
                tm.Rollback();
                HiddenFieldError.Value = ClassManager.CustomExceptionManager.Generate_Error(ex.Message);            
                showErrorMessage("No se pudo quitar la asoción del administrador, porque se encuentra asociado a otro registro.");
            }
        }

        private void ResizeGrids()
        { 
            float height = float.Parse(HiddenFieldHeight.Value.ToString()) - 25; 
            DeparmentsGrid.Height = Unit.Parse( (height / 2).ToString());
            AdministratorsSelectedGrid.Height = Unit.Parse((height - (height / 2)).ToString());
        }

        protected void DeparmentsGrid_NeedDataSource(object sender, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
        {
            GetDepartmentsByCompanies(getSessionManager().CompanyIDSelectedComboBox);
            ResizeGrids();
        }

        private void GetDepartmentsByCompanies(int companyID)
        {
            GPSTrackingDBV2.Entities.TList<GPSTrackingDBV2.Entities.CompaniesByDepartments> CompaniesByDepartmentsEntity = GPSTrackingDBV2.Data.DataRepository.CompaniesByDepartmentsProvider.GetByCompanyId(companyID);
            GPSTrackingDBV2.Data.DataRepository.CompaniesByDepartmentsProvider.DeepLoad(CompaniesByDepartmentsEntity, true, GPSTrackingDBV2.Data.DeepLoadType.IncludeChildren, typeof(GPSTrackingDBV2.Entities.Departments));
            DeparmentsGrid.DataSource = CompaniesByDepartmentsEntity;
        }

        protected void DeparmentsGrid_SelectedIndexChanged(object sender, EventArgs e)
        {
            int departmentID = getDepartmentIDSelected();
            HttpContext.Current.Session["DepartmentID"] = departmentID;

            setSessionManager(departmentID);

            GetAdministratorsByCompanyIDByDepartmentID(getSessionManager().CompanyIDSelectedComboBox, departmentID);
            AdministratorsSelectedGrid.DataBind();
            ResizeGrids();
        }

        protected int getDepartmentIDSelected()
        {

            try
            {
                foreach (Telerik.Web.UI.GridDataItem selectedItem in DeparmentsGrid.SelectedItems)
                {
                    return int.Parse(selectedItem["DepartmentId"].Text);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return -1;
        }

        private GPSTrackingDBV2.Entities.Departments Invoke_Entity(Hashtable Entity)
        {
            GPSTrackingDBV2.Entities.Departments DepartmentEntity = new GPSTrackingDBV2.Entities.Departments();
            DepartmentEntity.DepartmentId = Convert.ToInt32(Entity[GPSTrackingDBV2.Entities.DepartmentsColumn.DepartmentId.ToString()]);
            DepartmentEntity.Name = Entity["DepartmentIdSource.Name"].ToString();

            return DepartmentEntity;
        }

        protected void lbClearFilters_Click(object sender, EventArgs e)
        {
            DeparmentsGrid.MasterTableView.FilterExpression = string.Empty;

            foreach (GridColumn column in DeparmentsGrid.MasterTableView.RenderColumns)
            {
                if (column is GridBoundColumn)
                {
                    GridBoundColumn boundColumn = column as GridBoundColumn;
                    boundColumn.CurrentFilterValue = string.Empty;
                }
            }

            setSessionManager(-1);

            DeparmentsGrid.MasterTableView.Rebind();
            clearAdminGrid();
        }

        protected void lbClearFiltersAdmin_Click(object sender, EventArgs e)
        {
            AdministratorsSelectedGrid.MasterTableView.FilterExpression = string.Empty;

            foreach (GridColumn column in AdministratorsSelectedGrid.MasterTableView.RenderColumns)
            {
                if (column is GridBoundColumn)
                {
                    GridBoundColumn boundColumn = column as GridBoundColumn;
                    boundColumn.CurrentFilterValue = string.Empty;
                }
            }
            AdministratorsSelectedGrid.MasterTableView.Rebind();
        }

        public void showErrorMessage(string msg)
        {
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "objWindowsMessageManager.show_Error", "objWindowsMessageManager.show_Error('" + msg + "','Asociar Departamento al Administrador...');", true);
        }

        protected void DeparmentsGrid_ItemCommand(object sender, GridCommandEventArgs e)
        {
            if (e.CommandName == RadGrid.SortCommandName || e.CommandName == RadGrid.FilterCommandName)
            {
                clearAdminGrid();
                setSessionManager(-1);
            } 
        }

        private void clearAdminGrid(){
            HttpContext.Current.Session["DepartmentID"] = null;
            AdministratorsSelectedGrid.DataSource = new string[] { };
            AdministratorsSelectedGrid.DataBind();
        }

        protected void setSessionManager(int value)
        {
            SessionManager objSessionManager = (SessionManager)HttpContext.Current.Session["SessionManager"];
            objSessionManager.AdministratorsByDepartments_AdministratorsSeach_departmentID = value;
            HttpContext.Current.Session["SessionManager"] = objSessionManager;
        }

        protected SessionManager getSessionManager()
        {
            return (SessionManager)HttpContext.Current.Session["SessionManager"];
        }

        protected void lbShowError_Click(object sender, EventArgs e)
        {
            showErrorMessage(HiddenFieldError.Value);
        }

    }
}